import json
import os.path

from common.sql_constant_enum import bug_status_corresponding


# 处理状态码和返回信息
def add_reponse_code_msg(_data):
    _data.update({
        "code": 200,
        "msg": "success"
    })

# 处理数据为JSON格式
def serialize_json_dumps(origin_data):
    # 这里被迫处理响应的返回状态信息
    origin_data.update({
        "code": 200,
        "msg": "success"
    })
    return json.dumps(origin_data, ensure_ascii=False)


def find_2_item_in_list(goal, compare_list):
    count = 0
    for item in compare_list:
        if goal == item['name']:
            count += 1
    if count == 2:
        return 1
    else:
        return 0


def compute_rank_6_efficient(origin_list):
    # 获取所有的出现2次人员名单以及对应的数据
    person_set = {person['name'] for person in origin_list}
    person_num = 0
    person_efficient = -1
    person_score = {}
    for person in person_set:
        # print('------------------------------', person)
        if find_2_item_in_list(person, origin_list):
            # print('-------------', origin_list)
            for each_person in origin_list:
                if person == each_person['name']:
                    # 每个人的有效Bug数
                    person_efficient = int(each_person['count'])
                    if person not in person_score:
                        person_score[person] = [person_efficient]
                    else:
                        person_score[person].append( round(person_score[person][0] / int(each_person['count']) * 100, 2))
                        person_score[person].append( int(each_person['count']))
    return sorted(person_score.items(), key=lambda x: x[1][1], reverse=True)


from datetime import date, datetime

# datetime Json序列化
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)

def serialize_json_date_type(date_type):
    if date_type is None:
        return json.dumps(date_type, cls=ComplexEncoder)
    return json.dumps(date_type, cls=ComplexEncoder)[1:-1]


def down_chunk_file_manager(file_location, chuck_size=1024):
    """
    文件分片下发
    :param file_path:
    :param chuck_size:
    :return:
    """
    if not os.path.exists(file_location):
        print('-----------文件不存在-------------')
        return
    with open(file_location, "rb") as file:
        while True:
            chuck_stream = file.read(chuck_size)
            if chuck_stream:
                yield chuck_stream
            else:
                break


def write_download_file(file_localtion, columns, values):
    with open(file_localtion, "w", encoding='UTF-8') as file:
        print(*columns, sep=',', file=file)
        for each_value in values:
            print('-----------------------', each_value)
            print(*each_value, sep=',', file=file)


def transfer_dict_to_str(_dict):
    print('====================', _dict)
    str=''
    for key, value in _dict.items():
        str += '%s:%s&' % (bug_status_corresponding[key], value)
    return str[:-1]


def transfer_list_to_str(_list):
    print('====================', _list)
    str=''
    for each in _list:
        str += f' ~ {each}'
    return str

